package org.ezplatform.office.forum.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;
import javax.transaction.Transactional;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.org.OrgApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.component.permission.service.CmpApplyScopeService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.security.SecurityUtils;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.forum.dao.ForumBoardDao;
import org.ezplatform.office.forum.dao.ForumPostDao;
import org.ezplatform.office.forum.dao.ForumSensitiveDao;
import org.ezplatform.office.forum.entity.ForumBoard;
import org.ezplatform.office.forum.entity.ForumPost;
import org.ezplatform.office.forum.entity.ForumSensitive;
import org.ezplatform.office.forum.entity.ForumType;
import org.ezplatform.office.forum.util.sensitiveword.SensitiveUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.SqlUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;

/**
 * @desc 论坛版块service
 * @create 2017-11-15 19:50
 **/
/**
 * @author 15056
 *
 */
@Service
@Transactional
public class ForumBoardService extends BaseService<ForumBoard, String> {

	private final Logger LOGGER = LoggerFactory.getLogger(ForumBoardService.class);

	@Autowired
	private ForumBoardDao forumBoardDao;

	@Autowired
	private AttachmentUtilsService attachmentUtilsService;
	
	@Autowired
	private PopUserScopeUtilService popUserScopeUtilService;
	
	@Autowired
   	private CmpApplyScopeService cmpApplyScopeService;
	
	@Autowired
	private UserApiService userApiService;

	@Autowired
	private OrgApiService orgApiService;
	@Lazy
	@Autowired
	private ForumPostDao forumPostDao;
	@Lazy
	@Autowired
	private ForumTypeService forumTypeService;
	@Lazy
	@Autowired
	private ForumPostService forumPostService;
	
	@Autowired
	private ForumSensitiveDao forumSensitiveDao;
	
	@Autowired
	private LogService logService;

	@Override
	protected JpaBaseDao<ForumBoard, String> getEntityDao() {
		return forumBoardDao;
	}

	/**
	 * 
	 * @Title: findPage
	 * @Description: 分页查询
	 * 
	 * @param pageable
	 * @param filter
	 * @param corpId
	 * @return
	 * @return: Page<Map>
	 *
	 * @date 2017年11月17日 上午9:17:48
	 *
	 */
	public Page<Map> findPage(Pageable pageable, List<PropertyFilter> filter, String token, String corpId ,String typeId) {
		StringBuffer sql = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		sql.append(" select t.id, t.createdBy, t.authorName, t.createdDate, t.name, t.code, t.status, t.forumType, t.typeName, t.isAnonymity, t.isCheck, t.sortNo, t.description from ( ");
		sql.append(" select a.id as id, a.createdBy as createdBy, x.userName as authorName, a.createdDate as createdDate, a.name as name, a.code as code , a.status as status, a.forum_type as forumType, ");
		sql.append(" b.name as typeName, a.is_anonymity as isAnonymity, CASE WHEN a.is_check = '0' then '不审核' ELSE '审核' END  AS isCheck, a.sort_no as sortNo, a.description as description");
		sql.append(" FROM oa_forum_board a LEFT JOIN oa_forum_type b on a.forum_type = b.id ");
		sql.append(" left join  ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		sql.append(" on x.id = a.createdBy ");
		sql.append(" where a.corp_id = :corpId and a.is_delete = 0  ");
		if(StringUtils.isNotEmpty(typeId)) {
			sql.append(" AND b.id = :typeId ");
			values.put("typeId", typeId);
		}
		sql.append(" ) t where 1 = 1 ");
		values.put("corpId", corpId);
		String s = sql.toString();
		//获取查询和排序SQL
		s = PropertyFilter.getSqlByFilterAndPageable("t", s, " t.sortNo,t.createdDate desc ", filter, pageable);
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		return page;
	}

	/**
	 * 
	 * @Title: viewBoard
	 * @Description: 查看页面获取信息
	 * @param id
	 * @return
	 * @return: Map<String,Object>
	 *
	 * @date 2017年11月17日 下午2:42:20
	 *
	 */
	public Map<String, Object> viewBoard(String id) {
		// 获取基本信息
		String corpId = WebUtils.getCurrentUser().getCorpId();
		StringBuffer sql = new StringBuffer();
		sql.append(" select a.att_id as attId, a.id as id,a.aplication_scope as aplicationScope, a.createdBy as createdBy, a.createdDate as createdDate, a.name as name, a.code as code , a.status as status, a.forum_type as forumType, ");
		sql.append(" b.name as typeName, a.is_anonymity as isAnonymity, a.is_check as isCheck,a.is_petname as isPetname, a.sort_no as sortNo, a.description as description, a.is_navigation as isNavigation  ");
		sql.append(" FROM oa_forum_board a LEFT JOIN oa_forum_type b on a.forum_type = b.id and a.corp_id = b.corp_id and b.is_delete = 0 where a.corp_id = :corpId and a.id = :id and a.is_delete = 0 ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("corpId", corpId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
		Map<String, Object> result = new HashMap();
		if(list != null && !list.isEmpty()) {
			result = (Map<String, Object>)list.get(0);
		}
		return result;
	}

	/**
	 * 
	 * @Title: checkCodeUnique
	 * @Description: 编码唯一性校验
	 * 
	 * @param entity
	 * @return
	 * @return: boolean
	 *
	 * @date 2017年11月17日 下午3:49:25
	 *
	 */
	public boolean checkCodeUnique(String id,String code,String corpId) {
		boolean flag = false;
		ForumBoard board = forumBoardDao.getBoardByCode(code,corpId);
		if(id==null && board != null) {
			flag = true; 
		}else if(id != null && board != null && !id.equals(board.getId())) {
			flag = true; 
		}
		return flag;
	}

	/**
	 * 此方法代替orcal WM_CONCAT()函数，将需要拼接值的字段，单独拿出来查，形成一个map;
	 * value未拼接值，key为与主要查询关联的字段值
	 * @param mapList
	 */
	private Map<String, String> getMapWithKeyValue(String sql, Map<String, Object> paramMap, String key, String value) {
		List<Map> mapList = super.findByListNativeQuery(sql.toString(), null, paramMap);
		Map<String, String> m = new HashMap<String, String>();
		for(int i = 0; i < mapList.size(); i++) {
			String _key = mapList.get(i).get(key).toString();
			String _value =  (StringUtils.isBlank(mapList.get(i).get(value).toString()) ? "" : mapList.get(i).get(value).toString());
			if(StringUtils.isNotEmpty(m.get(_key))) {
				m.put(_key, m.get(_key) + "," + _value);
			}else {
				m.put(_key, _value);
			}
		}
		return m;
	}
	
	/*public List<Map<String,Object>> getForumNavInfo(String corpId,String token){
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		List<ForumType> typeList = forumTypeDao.getForumType(corpId);
		if(typeList != null && !typeList.isEmpty()){
			List<ForumBoard> boardList = forumBoardDao.getAllForumBoard(corpId);
			String s = "SELECT t.fieldDataValue, u.user_name AS moderator FROM oa_forum_moderator_scope t, sys_user u " + 
					"WHERE t.scopeType = 'user' AND t.scopeValue = u.id AND t.fieldDataTable = 'oa_forum_board' ";
			Map<String, String> map = getMapWithKeyValue(s, new HashMap<String, Object>(), "fieldDataValue", "moderator");
			for(ForumBoard fb : boardList) {
				fb.setModeratorName(map.get(fb.getId()));
			}
			List<ForumPost> postList = forumPostDao.getPostInfo(corpId);
		}
		return null;
	}*/
	
	/**
	 * 
	 * @Title: findForumNavigation
	 * @Description: 版块导航页面信息获取
	 * @param corpId
	 * @return
	 * @return: List<Map>
	 * @date 2017年11月20日 下午2:12:48
	 *
	 */
	public List<Map> findForumNavigation(String corpId, String token, WebUser user) {
		List<Map> result = new ArrayList<Map>();
		StringBuffer sql = new StringBuffer();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		sql.append(" select a.boardId,a.boardName,a.att_id,a.aplication_scope,a.typeId,a.isAnonymity,a.isCheck, ");
		sql.append(" a.sort_no,a.zts,a.tzs, ");
		sql.append(" t.name as typeName ");
		sql.append(" from ( ");
		sql.append(" select b.id as boardId, b.name as boardName,b.att_id,b.aplication_scope, b.forum_type as typeId,b.createdDate as createdDate, ");
		sql.append(" b.is_anonymity as isAnonymity, b.is_check as isCheck, ");
		sql.append(" b.sort_no, b.lastModifiedDate, ");
		sql.append(" count(CASE WHEN p.type = '1' and p.check_status in (:status) THEN p.id END ) AS zts, ");
		sql.append(" count(CASE WHEN p.type = '2' and p.check_status in (:status) THEN p.id END ) AS tzs ");
		sql.append(" from oa_forum_board b ");
		sql.append(" LEFT JOIN (SELECT p1.id,p1.type,p1.board_id,p1.is_delete,p1.check_status FROM oa_forum_post p1 ) p ");
		sql.append(" on b.id = p.board_id and p.is_delete = 0  ");
		sql.append(" WHERE b.corp_id = :corpId and b.status = 1 and b.is_delete = 0 ");
		sql.append(" GROUP BY b.id, b.name,b.att_id,b.aplication_scope, b.forum_type, b.is_anonymity, b.is_check, b.sort_no, b.lastModifiedDate, b.createdDate ) a, ");
		sql.append(" oa_forum_type t ");
		sql.append(" WHERE a.typeId = t.id and t.status = 1 and t.is_delete = 0 ");
		//适用范围sql匹配
		String scopeSql = cmpApplyScopeService.getInScopeDataSql(user.getUserId(), "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",paramMap);
		sql.append("and" + scopeSql);
		sql.append(" order by t.sort_no,t.createdDate desc,a.sort_no,a.createdDate desc ");
		List<String> checkStatus =new ArrayList<>();
		checkStatus.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		checkStatus.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		paramMap.put("corpId", corpId);
		paramMap.put("status", checkStatus);
		List<Map> boards = super.findByListNativeQuery(sql.toString(), null, paramMap);
		//敏感词初始化
		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : list) {
			if(StringUtils.isNoneEmpty(forumSensitive.getSensitiveName())) {
				sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
			}
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		
		String s = "SELECT t.fieldDataValue, u.user_name AS moderator FROM oa_forum_moderator_scope t, sys_user u " + 
				"WHERE t.scopeType = 'user' AND t.scopeValue = u.id AND t.fieldDataTable = 'oa_forum_board' ";
		Map<String, String> map = getMapWithKeyValue(s, new HashMap<String, Object>(), "fieldDataValue", "moderator");
		if(CollectionUtils.isNotEmpty(boards)) {
			for(Map<String, Object> m : boards) {
				//查询回帖数
				int rePost = getPostNum(m.get("boardId").toString(),"2",WebUtils.getCurrentUser().getCorpId());
				m.put("tzs", rePost);
				m.put("moderatorAllName", map.get(m.get("boardId")));
				//添加获取版块头像
				m.put("boardPhotoPath","");
				m.put("haveAvatar", false);
				if(StringUtils.isNotEmpty(StringUtils.null2String( m.get("att_id")))) {
					m.put("boardPhotoPath", GlobalConstant.getFlexServerPath(null) + "/"
							+ getBoardImg(m.get("att_id"), token));
					m.put("haveAvatar", true);
				}
			}
		}
		// 获取所有的版块id
		List<String> boardIds = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(boards)) {
		for (Map<String,Object> m : boards) {
			if (m.size()>0) {
				if (m.get("boardId") != null && StringUtils.isNotEmpty(String.valueOf(m.get("boardId")))) {
					boardIds.add(String.valueOf(m.get("boardId")));
				}
			}
		}
		}
		if (!CollectionUtils.isEmpty(boardIds)) {
			// 获取每个版块的最后一条发帖信息
			StringBuffer sql2 = new StringBuffer();
			sql2.append("select  o.id,o.title,o.board_id as boardId, o.publish_time as publishTime ");
			sql2.append(" from oa_forum_post o ");
			sql2.append(" where o.is_delete=0 and o.check_status in (:status) and o.type = 1");
			sql2.append(" ORDER BY createdDate desc,boardId desc,publish_time desc ");
			Map<String, Object> paramMap1 = new HashMap<String, Object>();
			paramMap1.put("status", checkStatus);
			List<Map> _zList = super.findByListNativeQuery(sql2.toString(), null, paramMap1);
			List<Map<String, Object>> zList = new ArrayList<Map<String, Object>>();
			List<String> postIdList = new ArrayList<String>();
			if(!CollectionUtils.isEmpty(_zList)) {
				Map<String,Object> eqMap = new HashMap<String,Object>();
				for(int i = 0; i < _zList.size(); i++) {
					Map<String,Object> bmap = new HashMap<String,Object>();
					String boardId = (String)_zList.get(i).get("boardId");
					String postId = (String)_zList.get(i).get("id");
					String title = (String)_zList.get(i).get("title");
					String publishTime = "";
					Date publishDate = (Date)_zList.get(i).get("publishTime");
					if(publishDate != null){
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						publishTime = sdf.format(_zList.get(i).get("publishTime"));
					}
					if(i==0 || !boardId.equals(eqMap.get("boardId"))){
						eqMap.put("boardId", boardId);
						bmap.put("boardId", boardId);
						bmap.put("postId", postId);
						bmap.put("title", title);
						bmap.put("publishTime", publishTime);
						postIdList.add(postId);
						zList.add(bmap);
					}
					
				}
			}
			/*if(postIdList != null && !postIdList.isEmpty()){
				String labelSQL = "SELECT ofl.color, ofl.name, ofp.post_id postId,ofp.id FROM oa_forum_label ofl LEFT JOIN oa_forum_post_label ofpl ON ofl.id = ofpl.label_id LEFT JOIN oa_forum_post ofp ON ofp.id = ofpl.post_id WHERE ofl.corp_id = '0' AND ofl.is_delete = 0 and ofp.id in (:postIdList)";
				Map<String, Object> pMap = new HashMap<String, Object>();
				pMap.put("postIdList",postIdList);
				List<Map> labelList = super.findByListNativeQuery(labelSQL, null, pMap);
				for(Map<String,Object> m : zList){
					String postId = (String)m.get("postId");
					List<Map<String,String>> labList = new ArrayList<Map<String,String>>();
					for(int i=0;i<labelList.size();i++){
						if(postId.equals(labelList.get(i).get("id"))){
							//最后发表评论的标签不得多于3个
							if(labList != null && labList.size()<3){
								labList.add(labelList.get(i));
							}
						}
					}
					m.put("postLabel", labList);
				}
			}*/
			
			// 遍历拼装分类数据，由于所有的boards已经按照 所属type的 sort_no和id进行排序过的，所有只需循环一次
			Map<String, Object> currentType = new HashMap<String, Object>();
			String tid = "";
			/*List<ForumPost> postList = forumPostDao.getPostInfo(corpId);
			Map<String,String> postMap1 = new HashMap<String,String>();
			for(ForumPost fp : postList){
				String paPostId = fp.getPostId();
				String poId = fp.getId();
				if(StringUtils.isNotEmpty(paPostId)){
					postMap1.put(poId,paPostId);
				}else{
					postMap1.put(poId,poId);
				}
			}*/
			for (Map<String,Object> b : boards) {
				boolean flag = false;
				String boardId = (String)b.get("boardId");
				for(int i=0;i<zList.size();i++){
					Map<String,Object> pm = zList.get(i); 
					if(boardId.equals(pm.get("boardId"))){
						//String paPostId = postMap1.get((String)pm.get("postId"));
						b.put("postId", pm.get("postId"));
						//b.put("paPostId", paPostId);
						b.put("paPostId", pm.get("postId"));
						if(sensitiveList!=null&&sensitiveList.size()>0) {
							b.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, pm.get("title").toString(), 2, "*"));
						}else {
							b.put("title", pm.get("title").toString());
						}
						b.put("publishTime", pm.get("publishTime"));
						b.put("postLabel", pm.get("postLabel"));
						b.put("clickTitle", true);
						flag = true;
						break;
					}
				}
				if(!flag) {
					b.put("title", "暂无数据");
					b.put("clickTitle", false);
				}
				if (StringUtils.equals(tid, b.get("typeId").toString())) {
					// 将当前board放入 currentType分类中
					pushCurrentType(currentType, b);
				} else {
					// 更新当前缓存信息
					if (StringUtils.isNotEmpty(tid)) {
						result.add(currentType);
						currentType = new HashMap<String, Object>();
					}
					tid = b.get("typeId").toString();
					currentType.put("typeId", tid);
					currentType.put("typeName", b.get("typeName"));
					pushCurrentType(currentType, b);
				}
			}
			result.add(currentType);
		}
		if (CollectionUtils.isEmpty(result)) {
			Map m = new HashMap();
			m.put("typeId", 0);
			m.put("typeName", "初始化版块");
			m.put("boards", new ArrayList());
			result.add(m);
			return result;
		}else {
			return result;
		}
	}

	/**
	 * 
	 * @Title: findMDForumNavigation
	 * @Description: 版主版块导航页面信息获取
	 * @param corpId
	 * @return
	 * @return: List<Map>
	 * @date 2017年11月20日 下午2:12:48
	 *
	 */
	public List<Map> findMDForumNavigation(String corpId, String token, WebUser user) {
		List<Map> result = new ArrayList<Map>();
		StringBuffer sql = new StringBuffer();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		sql.append(" select a.boardId,a.boardName,a.att_id,a.aplication_scope,a.typeId,a.isAnonymity,a.isCheck, ");
		sql.append(" a.sort_no,fn_date_format(a.lastModifiedDate,'MM-dd HH:mm') lastModifiedDate,a.zts,a.tzs,fn_date_format(a.createdDate,'MM-dd HH:mm') createdDate, ");
		sql.append(" t.name as typeName ");
		sql.append(" from ( ");
		sql.append(" select b.id as boardId, b.name as boardName,b.att_id,b.aplication_scope, b.forum_type as typeId,b.createdDate as createdDate, ");
		sql.append(" b.is_anonymity as isAnonymity, b.is_check as isCheck, ");
		sql.append(" b.sort_no, b.lastModifiedDate, ");
		sql.append(" count(CASE WHEN p.type = '1' and p.check_status in (:status) THEN p.id END ) AS zts, ");
		sql.append(" count(CASE WHEN p.type = '2' and p.check_status in (:status) THEN p.id END ) AS tzs ");
		sql.append(" from oa_forum_board b ");
		sql.append(" LEFT JOIN (SELECT p1.id,p1.type,p1.board_id,p1.is_delete,p1.check_status FROM oa_forum_post p1 ) p ");
		sql.append(" on b.id = p.board_id and p.is_delete = 0  ");
		sql.append(" WHERE b.corp_id = :corpId and b.status = 1 and b.is_delete = 0 ");
		sql.append(" GROUP BY b.id, b.name,b.att_id,b.aplication_scope, b.forum_type, b.is_anonymity, b.is_check, b.sort_no, b.lastModifiedDate, b.createdDate ) a, ");
		sql.append(" oa_forum_type t ");
		sql.append(" WHERE a.typeId = t.id and t.status = 1 and t.is_delete = 0 ");
		//适用范围sql匹配
		//String scopeSql = cmpApplyScopeService.getInScopeDataSql(user.getUserId(), "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",paramMap);
		//sql.append("and" + scopeSql);
		//适用版主sql匹配
		//String moderatorSql = cmpApplyScopeService.getInScopeDataSql(user.getUserId(), "oa_forum_moderator_scope", "oa_forum_board", "id",paramMap);
		sql.append(" and (boardId in ( select fieldDataValue from oa_forum_moderator_scope where  fieldData='id' and fieldDataTable='oa_forum_board' and scopeValue in  (:userId)))" );
		sql.append(" order by t.sort_no,t.createdDate desc,a.sort_no,a.createdDate desc ");
		List<String> checkStatus =new ArrayList<>();
		checkStatus.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		checkStatus.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		paramMap.put("corpId", corpId);
		paramMap.put("status", checkStatus);
		paramMap.put("userId", user.getUserId());
		List<Map> boards = super.findByListNativeQuery(sql.toString(), null, paramMap);
		//敏感词初始化
		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : list) {
			if(StringUtils.isNoneEmpty(forumSensitive.getSensitiveName())) {
				sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
			}
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		
		String s = "SELECT t.fieldDataValue, u.user_name AS moderator FROM oa_forum_moderator_scope t, sys_user u " + 
				"WHERE t.scopeType = 'user' AND t.scopeValue = u.id AND t.fieldDataTable = 'oa_forum_board' ";
		Map<String, String> map = getMapWithKeyValue(s, new HashMap<String, Object>(), "fieldDataValue", "moderator");
		if(CollectionUtils.isNotEmpty(boards)) {
			for(Map<String, Object> m : boards) {
				//查询回帖数
				int rePost = getPostNum(m.get("boardId").toString(),"2",WebUtils.getCurrentUser().getCorpId());
				m.put("tzs", rePost);
				m.put("moderatorAllName", map.get(m.get("boardId")));
				//添加获取版块头像
				m.put("boardPhotoPath","");
				m.put("haveAvatar", false);
				if(StringUtils.isNotEmpty(StringUtils.null2String( m.get("att_id")))) {
					m.put("boardPhotoPath", GlobalConstant.getFlexServerPath(null) + "/"
							+ getBoardImg(m.get("att_id"), token));
					m.put("haveAvatar", true);
				}
			}
		}
		// 获取所有的版块id
		List<String> boardIds = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(boards)) {
		for (Map<String,Object> m : boards) {
			if (m.size()>0) {
				if (m.get("boardId") != null && StringUtils.isNotEmpty(String.valueOf(m.get("boardId")))) {
					boardIds.add(String.valueOf(m.get("boardId")));
				}
			}
		}
		}
		if (!CollectionUtils.isEmpty(boardIds)) {
			// 获取每个版块的最后一条发帖信息
			StringBuffer sql2 = new StringBuffer();
			sql2.append("select  o.id,o.title,o.board_id as boardId, o.publish_time as publishTime ");
			sql2.append(" from oa_forum_post o ");
			sql2.append(" where o.is_delete=0 and o.check_status in (:status) and o.type = 1");
			sql2.append(" ORDER BY createdDate desc,boardId desc,publish_time desc ");
			Map<String, Object> paramMap1 = new HashMap<String, Object>();
			paramMap1.put("status", checkStatus);
			List<Map> _zList = super.findByListNativeQuery(sql2.toString(), null, paramMap1);
			List<Map<String, Object>> zList = new ArrayList<Map<String, Object>>();
			List<String> postIdList = new ArrayList<String>();
			if(!CollectionUtils.isEmpty(_zList)) {
				Map<String,Object> eqMap = new HashMap<String,Object>();
				for(int i = 0; i < _zList.size(); i++) {
					Map<String,Object> bmap = new HashMap<String,Object>();
					String boardId = (String)_zList.get(i).get("boardId");
					String postId = (String)_zList.get(i).get("id");
					String title = (String)_zList.get(i).get("title");
					String publishTime = "";
					Date publishDate = (Date)_zList.get(i).get("publishTime");
					if(publishDate != null){
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						publishTime = sdf.format(_zList.get(i).get("publishTime"));
					}
					if(i==0 || !boardId.equals(eqMap.get("boardId"))){
						eqMap.put("boardId", boardId);
						bmap.put("boardId", boardId);
						bmap.put("postId", postId);
						bmap.put("title", title);
						bmap.put("publishTime", publishTime);
						postIdList.add(postId);
						zList.add(bmap);
					}
					
				}
			}
			/*if(postIdList != null && !postIdList.isEmpty()){
				String labelSQL = "SELECT ofl.color, ofl.name, ofp.post_id postId,ofp.id FROM oa_forum_label ofl LEFT JOIN oa_forum_post_label ofpl ON ofl.id = ofpl.label_id LEFT JOIN oa_forum_post ofp ON ofp.id = ofpl.post_id WHERE ofl.corp_id = '0' AND ofl.is_delete = 0 and ofp.id in (:postIdList)";
				Map<String, Object> pMap = new HashMap<String, Object>();
				pMap.put("postIdList",postIdList);
				List<Map> labelList = super.findByListNativeQuery(labelSQL, null, pMap);
				for(Map<String,Object> m : zList){
					String postId = (String)m.get("postId");
					List<Map<String,String>> labList = new ArrayList<Map<String,String>>();
					for(int i=0;i<labelList.size();i++){
						if(postId.equals(labelList.get(i).get("id"))){
							//最后发表评论的标签不得多于3个
							if(labList != null && labList.size()<3){
								labList.add(labelList.get(i));
							}
						}
					}
					m.put("postLabel", labList);
				}
			}*/
			
			// 遍历拼装分类数据，由于所有的boards已经按照 所属type的 sort_no和id进行排序过的，所有只需循环一次
			Map<String, Object> currentType = new HashMap<String, Object>();
			String tid = "";
			/*List<ForumPost> postList = forumPostDao.getPostInfo(corpId);
			Map<String,String> postMap1 = new HashMap<String,String>();
			for(ForumPost fp : postList){
				String paPostId = fp.getPostId();
				String poId = fp.getId();
				if(StringUtils.isNotEmpty(paPostId)){
					postMap1.put(poId,paPostId);
				}else{
					postMap1.put(poId,poId);
				}
			}*/
			for (Map<String,Object> b : boards) {
				boolean flag = false;
				String boardId = (String)b.get("boardId");
				for(int i=0;i<zList.size();i++){
					Map<String,Object> pm = zList.get(i); 
					if(boardId.equals(pm.get("boardId"))){
						//String paPostId = postMap1.get((String)pm.get("postId"));
						b.put("postId", pm.get("postId"));
						//b.put("paPostId", paPostId);
						b.put("paPostId", pm.get("postId"));
						if(sensitiveList!=null&&sensitiveList.size()>0) {
							b.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, pm.get("title").toString(), 2, "*"));
						}else {
							b.put("title", pm.get("title").toString());
						}
						b.put("publishTime", pm.get("publishTime"));
						b.put("postLabel", pm.get("postLabel"));
						b.put("clickTitle", true);
						flag = true;
						break;
					}
				}
				if(!flag) {
					b.put("title", "暂无数据");
					b.put("clickTitle", false);
				}
				if (StringUtils.equals(tid, b.get("typeId").toString())) {
					// 将当前board放入 currentType分类中
					pushCurrentType(currentType, b);
				} else {
					// 更新当前缓存信息
					if (StringUtils.isNotEmpty(tid)) {
						result.add(currentType);
						currentType = new HashMap<String, Object>();
					}
					tid = b.get("typeId").toString();
					currentType.put("typeId", tid);
					currentType.put("typeName", b.get("typeName"));
					pushCurrentType(currentType, b);
				}
			}
			result.add(currentType);
		}
		if (CollectionUtils.isEmpty(result)) {
			Map m = new HashMap();
			m.put("typeId", 0);
			m.put("typeName", "初始化版块");
			m.put("boards", new ArrayList());
			result.add(m);
			return result;
		}else {
			return result;
		}
	}
	
	private void pushCurrentType(Map<String, Object> c, Map b) {
		if (c != null) {
			if (StringUtils.equals(c.get("typeId").toString(), b.get("typeId").toString())) {
				Object boards = c.get("boards");
				if (boards != null && boards instanceof ArrayList) {
					((List) boards).add(b);
				} else if (boards == null) {
					boards = new ArrayList<String>();
					((List) boards).add(b);
				}
				c.put("boards", boards);
			}
		}
	}

	/**
	 * 
	 * @Title: updateModerator
	 * @Description: 更新 oa_forum_board表中的 版主信息
	 * @param id
	 * @return: void
	 *
	 * @date 2017年11月21日 上午11:47:06
	 *
	 */
	public void updateModerator(String token, String id) {
		if (StringUtils.isNotBlank(id)) {
			String moderatorName = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope",
					"oa_forum_board", "id", StringUtils.null2String(id));
			Map<String, String> param = new HashMap<String, String>();
			param.put("corpId", WebUtils.getCurrentUser().getCorpId());
			param.put("scopeTypeValue", moderatorName);
			String moderatorNameStr = userApiService.getScopeName(moderatorName, WebUtils.getCurrentUser().getCorpId(),
					token);
			forumBoardDao.updateModerator(moderatorNameStr, id);
		}
	}

	/**
	 * 
	 * @Title: findAllBoards
	 * @Description: 根据corpId获取所有的版块信息
	 * @param corpId
	 * @return
	 * @return: List<ForumBoard>
	 *
	 * @date 2017年11月22日 下午2:23:12
	 *
	 */
//	public List<ForumBoard> findAllBoards(String corpId) {
//		String sql = " select * from oa_forum_board where corp_id = ?1 and status = 1 and is_delete = 0 order by sort_no, createdDate desc, id";
//		return this.getEntityManager().createNativeQuery(sql, ForumBoard.class).setParameter(1, corpId).getResultList();
//	}

	/**
	 *
	 * @Title: findAllBoards
	 * @Description: 根据corpId获取所有有效分类下有效的版块信息
	 * @param corpId
	 * @return
	 * @return: List<ForumBoard>
	 *
	 * @date 2017年11月22日 下午2:23:12
	 *
	 */
	public List<Map> findAllBoardsOnType(String corpId) {
		String sql = " select b.id as id,b.name as name,b.is_anonymity as isAnonymity from oa_forum_board b, oa_forum_type t where b.forum_type = t.id and  b.corp_id = :corpId and b.status = 1 and b.is_delete = 0 and t.corp_id = :corpId and t.status = 1 and t.is_delete = 0 order by b.sort_no, b.createdDate desc, b.id";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", corpId);
		return super.findByListNativeQuery(sql.toString(), null, paramMap);
	}

	/**
	 * 
	 * @Title: getTypeBoardTree
	 * @Description: 获取类型、版块树
	 * @return
	 * @return: List<Map>
	 *
	 * @date 2017年11月24日 上午9:23:45
	 *
	 */
	public List<Map> getTypeBoardTree(String name, String corpId,String withoutBoard,WebUser user) {
		List<Map> r = getTypeBoardTressSourceData(name, corpId,withoutBoard,user.getUserId());
		List<Map> g = new ArrayList<Map>();
		Iterator it = r.iterator();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			if (null != m.get("id")) {
				g.add(createTreeNode(m.get("id").toString(), m.get("name").toString(), m.get("pid") == null||"".equals(m.get("pid").toString().trim()) ? "1" : m.get("pid").toString()));
			}
		}
		return g;
	}
	
	/**
	 * 
	 * @Title: getMDTypeBoardTree
	 * @Description: 获取版主类型、版块树
	 * @return
	 * @return: List<Map>
	 *
	 * @date 2017年11月24日 上午9:23:45
	 *
	 */
	public List<Map> getMDTypeBoardTree(String name, String corpId,String withoutBoard,WebUser user) {
		List<Map> r = getMDTypeBoardTressSourceData(name, corpId,withoutBoard,user.getUserId());
		List<Map> g = new ArrayList<Map>();
		Iterator it = r.iterator();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			if (null != m.get("id")) {
				g.add(createTreeNode(m.get("id").toString(), m.get("name").toString(), m.get("pid") == null||"".equals(m.get("pid").toString().trim()) ? "1" : m.get("pid").toString()));
			}
		}
		return g;
	}

	/**
	 * 获取类型、版块树 -- 钉钉app获取数据
	 * 
	 * @param name
	 * @param corpId
	 * @return
	 */
	public List<Map> getTypeBoardTreeWithDDApp(String name, String corpId,String userId) {
		List<Map> resutl = getTypeBoardTressSourceData(name, corpId,"1",userId);
		//敏感词初始化
		List<ForumSensitive> senlist =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : senlist) {
			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		for (Map map : resutl) {
			String id = map.get("id").toString();
			int postCount = this.getPostNum(id,"1",WebUtils.getCurrentUser().getCorpId());
			map.put("postCount", postCount);
            int replyCount = this.getPostNum(id,"2",WebUtils.getCurrentUser().getCorpId());
            map.put("replyCount", replyCount);
            List<Map> title = forumPostService.getLastTitleByBoardId(id);
            if(title!=null &&title.size()>0) {
            	//敏感词替换
    			if(sensitiveList!=null&&sensitiveList.size()>0) {
    				map.put("lastTitle", SensitiveUtils.replaceSensitiveWord(initKeyWord,title.get(0).get("title").toString(), 2, "*"));
    			}
            }else {
            	 map.put("lastTitle", "暂无");
            }
           
		}
		// 重新封装数据格式
		//存放类别
		List<Map> types = new ArrayList<>();
		//存放板块
		Map<String, List> swap = new HashMap<>();
		Iterator r1 = resutl.iterator();
		while (r1.hasNext()) {
			Map m = (Map) r1.next();
			String type = StringUtils.isNotBlank(StringUtils.null2String(m.get("pid"))) ? "2":"1";
			m.put("type", type);
			//如果是类别
			if (StringUtils.equals("1", type)) {
				types.add(m);
			}
			//如果是版块,再处理下附件文件
			if (StringUtils.equals("2", type)) {
				String attId = StringUtils.null2String(m.get("attId"));
				int imageNum = 0;
				if(attId !=null&&StringUtils.isNotBlank(attId)) {
					imageNum =  attId.split("\\|").length;
				}
				m.put("imageNum", imageNum);
				m.put("attIdJson",forumPostService.transformAttachmentPlanform2Dd(attId));
				String typeid = StringUtils.null2String(m.get("pid"));
				List typeList = swap.get(typeid);
				if (typeList == null) {
					typeList = new ArrayList();
				}
				typeList.add(m);
				swap.put(typeid, typeList);
			}
		}
		Iterator t1 = types.iterator();
		while (t1.hasNext()) {
			Map m = (Map) t1.next();
			List boards = swap.get(StringUtils.null2String(m.get("id")));
				m.put("boardArray", boards);
		}
		//筛选没有板块的类别，根据需求变
		List<Map> typesNew = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(types)) {
			for (Map map : types) {
				//需求变动，没有版块仍需展示
				/*List boardArray= (List) map.get("boardArray");
				if(CollectionUtils.isNotEmpty(boardArray)) {
					typesNew.add(map);
				}*/
				typesNew.add(map);
			}
		}
		return typesNew;
	}

	/**
	 * 获取类别、版块树 --- 原始数据
	 * 
	 * @param name
	 * @param corpId
	 * @return
	 */
	public List<Map> getTypeBoardTressSourceData(String name, String corpId ,String withoutBoard,String userId) {
		StringBuffer sql = new StringBuffer();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		sql.append(" select attId,id,name,pid,aplication_scope,description,sortno,createddate from ( ");
		if(StringUtils.equals(withoutBoard, "1")) {
			sql.append(" select b.name, b.att_id AS attId,b.id,b.aplication_scope, b.forum_type as pid, b.description,b.sort_no as sortno,b.createdDate as createddate from oa_forum_board b, oa_forum_type x where b.forum_type = x.id and b.status = 1 and b.is_delete = 0 and b.corp_id = :corpId ");
			sql.append(" and x.is_delete = 0 and x.status = 1 and x.corp_id = :corpId ");
			sql.append(" union  ");
		}
		sql.append(" select  t.name, ' ' AS attId, t.id,  ' ' as pid, ' ' as aplication_scope , t.description,t.sort_no as sortno,t.createdDate as createddate from oa_forum_type t where   ");
		//版块管理显示被禁用的类别
		if(StringUtils.equals(withoutBoard, "1")) {
			sql.append(" t.status = 1 and ");
		}
		sql.append("  t.is_delete = 0 and t.corp_id = :corpId ) a ");
		if (StringUtils.isNotEmpty(name)) {
			sql.append(" where a.name like :name "  + SqlUtils.getSQLEscape(name));
			name = SqlUtils.escapeNormalChars(name);
			paramMap.put("name", "%" + name + "%");
		}
		//版块导航适用范围sql匹配
		if(StringUtils.equals(withoutBoard, "1")) {
			String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",paramMap);
			if(StringUtils.isNotBlank(name)) {
				sql.append(" and " + scopeSql);
			}else {
				sql.append(" Where " + scopeSql);
			}
		}
		sql.append(" order by a.sortno,a.createddate desc ");
		paramMap.put("corpId", corpId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
		return list;
	}
	
	/**
	 * 获取版主类别、版块树 --- 原始数据
	 * 
	 * @param name
	 * @param corpId
	 * @return
	 */
	public List<Map> getMDTypeBoardTressSourceData(String name, String corpId ,String withoutBoard,String userId) {
		StringBuffer sql = new StringBuffer();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		sql.append(" select attId,id,name,pid,aplication_scope,description,sortno,createddate from ( ");
		if(StringUtils.equals(withoutBoard, "1")) {
			sql.append(" select b.name, b.att_id AS attId,b.id,b.aplication_scope, b.forum_type as pid, b.description,b.sort_no as sortno,b.createdDate as createddate from oa_forum_board b, oa_forum_type x where b.forum_type = x.id and b.status = 1 and b.is_delete = 0 and b.corp_id = :corpId ");
			sql.append(" and x.is_delete = 0 and x.status = 1 and x.corp_id = :corpId ");
			//适用版主sql匹配
			sql.append(" and (b.id in ( select fieldDataValue from oa_forum_moderator_scope where  fieldData='id' and fieldDataTable='oa_forum_board' and scopeValue in  (:userId)))" );
			sql.append(" union  ");
		}
		sql.append(" select  t.name, ' ' AS attId, t.id,  ' ' as pid, ' ' as aplication_scope , t.description,t.sort_no as sortno,t.createdDate as createddate from oa_forum_type t where   ");
		//版块管理显示被禁用的类别
		if(StringUtils.equals(withoutBoard, "1")) {
			sql.append(" t.status = 1 and ");
		}
		sql.append("  t.is_delete = 0 and t.corp_id = :corpId ) a ");
		if (StringUtils.isNotBlank(name)) {
			sql.append(" where a.name like " + SqlUtils.escapeLikeValue(name));
		}
		//版块导航适用范围sql匹配
		if(StringUtils.equals(withoutBoard, "1")) {
			String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",paramMap);
			if(StringUtils.isNotBlank(name)) {
				sql.append(" and " + scopeSql);
			}else {
				sql.append(" Where " + scopeSql);
			}
		}
		sql.append(" order by a.sortno,a.createddate desc ");
		paramMap.put("corpId", corpId);
		paramMap.put("userId", userId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
		return list;
	}

	/**
	 * 树结构为3层
	 * 第一层全部，第二层类别，第三层版块
	 * string3 值为1时，是处于第2层
	 * @param string
	 * @param string2
	 * @param string3
	 * @return
	 */
	private Map createTreeNode(String string, String string2, String string3) {
		Map m = new HashMap();
		m.put("id", string);
		m.put("pId", string3);
		m.put("linkName", string2);
		m.put("isSysInit", "0");
		m.put("name", string2);
		// m.put("osu", "org");
		if("1".equals(string3)) {
			m.put("open",  true);
		}else {
			m.put("open", StringUtils.isEmpty(string3) ? true : false);
		}
		m.put("checked",false);
		if("1".equals(string3)) {
			m.put("type",  2);
		}else {
			m.put("type", StringUtils.isEmpty(string3) ? 1 : 3);
		}
		
		if("1".equals(string3)) {
			m.put("nocheck",  true);
		}else {
			m.put("nocheck", StringUtils.isEmpty(string3) ? true : false);
		}
		return m;
	}

	/**
	 * 
	 * @Title: getUserBoards
	 * @Description: 获取当前用户管理的版块
	 * @return
	 * @return: List<String>
	 *
	 * @date 2017年11月28日 上午11:57:24
	 *
	 */
	public List<String> getUserBoards() {
		List<String> r = new ArrayList<String>();
		WebUser user = WebUtils.getCurrentUser();
		StringBuffer s0 = new StringBuffer();
		s0.append(" select b.id from oa_forum_moderator_scope s, oa_forum_board b where s.fieldDataValue = b.id and s.scopeType = 'user' and b.corp_id = ?1 ");
		if(!"admin".equals(user.getUserName())) {
			s0.append("and s.scopeValue = '" + user.getUserId() + "'");
		}
		Query q0 = this.getEntityManager().createNativeQuery(s0.toString()).setParameter(1,user.getCorpId());
		r = q0.getResultList();
		return r;
	}

	/**
	 * 
	 * @Title: IsModeratorOfBoard
	 * @Description: 判断当前用户是否为 该版块的版主
	 * @param boardId
	 * @return
	 * @return: boolean
	 *
	 * @date 2017年11月28日 下午12:43:48
	 *
	 */
	public boolean IsModeratorOfBoard(String boardId) {
		boolean isModerator = false;
		WebUser user = WebUtils.getCurrentUser();
		String s0 = " select b.id from oa_forum_moderator_scope s, oa_forum_board b where s.fieldDataValue = b.id and s.scopeType = 'user' and s.scopeValue = ?1 and b.corp_id = ?2 and b.id = ?3 ";
		Query q0 = this.getEntityManager().createNativeQuery(s0).setParameter(1, user.getUserId())
				.setParameter(2, user.getCorpId()).setParameter(3, boardId);
		List r0 = q0.getResultList();
		if (r0 != null && !CollectionUtils.isEmpty(r0)) {
			isModerator = true;
		}
		return isModerator;
	}

	/**
	 * 
	 * @Title: currentuserIsModerator
	 * @Description: 判断当前用户是否为 所给版块的版主
	 * @param postId
	 * 
	 * @return: boolean
	 *
	 * @date 2017年11月28日 下午12:36:37
	 *
	 */
	public boolean IsModeratorOfPost(String postId) {
		boolean isModerator = false;
		WebUser user = WebUtils.getCurrentUser();
		// 判断当前用户是否为该帖子所在版块的版主------------修改为：只要是自己的帖子都可以编辑
		StringBuffer s0 = new StringBuffer();
		 s0.append( " select s.id from oa_forum_moderator_scope s, oa_forum_post p where s.fieldDataValue = p.board_id and s.scopeType = 'user' and s.scopeValue = ?1 and p.id = ?2 ");
		s0.append(" UNION select s.id from oa_forum_moderator_scope s, oa_forum_post p  where s.fieldDataValue = p.board_id and s.scopeType = 'user' ");
		s0.append(" and p.author = ?3 and p.id = ?4  and s.scopeValue=?5");
		Query q0 = this.getEntityManager().createNativeQuery(s0.toString()).setParameter(1, user.getUserId()).setParameter(2,
				postId).setParameter(3, user.getUserId()).setParameter(4, postId).setParameter(5, user.getUserId());
		List r0 = q0.getResultList();
		if (r0 != null && !CollectionUtils.isEmpty(r0)) {
			isModerator = true;
		}
		return isModerator;
	}
	
	/**
	 * 逻辑删除一个版块
	 * @param id
	 * @return
	 */
	public OperationResult logicDeleteOne(String... id) {
		int delNum = forumBoardDao.setBoardDel(1, Arrays.asList(id));
		List<ForumBoard> boardList = forumBoardDao.getForumBoardList(Arrays.asList(id));
		for (ForumBoard board : boardList) {
			if(Arrays.asList(id).contains(board.getId())) {
				logService.saveModuleLog("forum:board:04", board.getName(), ""); 
			}
		}
		Map resources = new HashMap();
		//国际化资源
		resources.put("i18NCode", "oa.forum.deletetips4");
		return OperationResult.buildSuccessResult("删除成功",resources);
	}
	

	/**
	 *
	 * @Title: logicDelete
	 * @Description: 逻辑删除信息
	 * @param ids
	 *
	 * @return: boolean
	 *
	 * @date 2017年12月7日 下午12:36:37
	 *
	 */
	public OperationResult logicDelete(String[] ids) {
		List<String> idList = Arrays.asList(ids);
		StringBuffer s0 = new StringBuffer();
		s0.append(" SELECT c.id boardId, CASE WHEN p.count IS NULL THEN 0 ELSE p.count END AS count ");
		s0.append(" FROM ( SELECT b.id FROM oa_forum_board b WHERE ");
		s0.append(" b.id IN (:boardId) AND b.is_delete = :isDelete ) c ");
		s0.append(" LEFT JOIN ( SELECT p.board_id boardId, count(p.board_id) AS count FROM oa_forum_post p ");
		s0.append(" WHERE p.board_id IN (:boardId) AND p.is_delete = :isDelete AND p.check_status IN (1,2,4) AND p.type = '1' GROUP BY p.board_id ) p ON p.boardId = c.id ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("boardId", idList);
		paramMap.put("isDelete", 0);
		List<Map> r0 = super.findByListNativeQuery(s0.toString(), null, paramMap);
		int fDelNum = 0;
		int delNum = 0;
		//可以删除的版块list
		List<String> delList = new ArrayList<String>();
		//不可以删除的版块list
		List<String> fdelList = new ArrayList<String>();
		for (Map map : r0) {
			if(Integer.parseInt(map.get("count").toString()) > 0) {
				fdelList.add(map.get("boardId").toString());
				fDelNum++;
			}else {
				delList.add(map.get("boardId").toString());
				delNum++ ;
			}
		}
		if(delList != null && !delList.isEmpty()){
			delNum = forumBoardDao.setBoardDel(1, delList);
			List<ForumBoard> boardList = forumBoardDao.getForumBoardList(delList);
			for (ForumBoard board : boardList) {
				if(delList.contains(board.getId())) {
					logService.saveModuleLog("forum:board:04", board.getName(), ""); 
				}
			}
		}
		if(fdelList != null && !fdelList.isEmpty()){
			List<ForumBoard> boardList = forumBoardDao.getForumBoardList(fdelList);
			for (ForumBoard board : boardList) {
					logService.saveModuleLog("forum:board:04", board.getName(),"", UuidUtils.UUID()); 
			}
		}
		String msg = "成功删除版块" +delNum+ "个";
		if(fDelNum != 0){
			//msg +=",存在"+fDelNum+"个有主题帖的版块不可删除";
			msg=delNum+"|"+fDelNum;
			return OperationResult.buildFailureResult(msg);
		}else{
			Map resources = new HashMap();
			//国际化资源
			resources.put("i18NCode", "oa.forum.deletetips4");
			msg = "删除成功";
			return OperationResult.buildSuccessResult(msg,resources);
		}
		
//		List<ForumPost> postList = forumPostDao.getPostByBoard(idList, 0);
//		int fDelNum = 0;
//		int delNum = 0;
//		List<String> delList = new ArrayList<String>();
//		if(postList != null && !postList.isEmpty()){
//			fDelNum = postList.size();
//			if(idList.size() == fDelNum){
//				return OperationResult.buildFailureResult("所选版块下存在主题帖无法删除");
//			}else{
//				for(String id : idList){
//					if(!postList.contains(id)){
//						delList.add(id);
//					}
//				}
//			}
//		}else{
//			delList = idList;
//		}
//		if(delList != null && !delList.isEmpty()){
//			delNum = forumBoardDao.setBoardDel(1, delList);
//			List<ForumBoard> boardList = forumBoardDao.getForumBoardList(delList);
//			for (ForumBoard board : boardList) {
//				if(delList.contains(board.getId())) {
//					logService.saveModuleLog("forum:board:04", board.getName(), ""); 
//				}
//			}
//		}
//		String msg = "成功删除版块" +delNum+ "个";
//		if(fDelNum != 0){
//			msg +=",存在"+fDelNum+"个有主题帖的版块不可删除";
//		}else{
//			msg = "删除成功";
//		}
//		return OperationResult.buildSuccessResult(msg);
	}


	/**
	 *
	 * @Title: getBoardModeratorInfoById
	 * @Description: 根据id获取某个版块的版主信息
	 * @param id
	 *
	 * @return: boolean
	 *
	 * @date 2017年12月7日 下午19:36:37
	 *
	 */
	public Map getBoardModeratorInfoById(String token, String id) {
		Map m = new HashMap();
		if (StringUtils.isNotBlank(id)) {
			ForumBoard forumBoard = this.findOne(id);
			if (forumBoard != null) {
				m.put("id", id);
				m.put("name", forumBoard.getName());
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("id",id);
				String sql = "select b.id as id, s.scopeValue as boardModeratorId from oa_forum_board b LEFT JOIN oa_forum_moderator_scope s on s.fieldDataValue = b.id and s.scopeType = 'user' where  b.id = :id";
				Map<String, String> map = getMapWithKeyValue(sql, paramMap, "id", "boardModeratorId");
				m.put("boardModeratorId", map.get(id));
				List<String> userids = Arrays
						.asList(StringUtils.split(StringUtils.null2String(m.get("boardModeratorId")), ","));
				Map<String, String> userMap = utilQueryUserName2(StringUtils.join(userids, ","),
						WebUtils.getCurrentUser().getCorpId(), token);

				List<String> moderators = Arrays.asList(StringUtils.null2String(m.get("boardModeratorId")).split(","));
				List<String> moderatorsName = new ArrayList<String>();
				for (String str : moderators) {
					moderatorsName.add("".equals(StringUtils.null2String(userMap.get(str))) ? "用户未找到" : StringUtils.null2String(userMap.get(str)));
				}
				m.put("boardModeratorName", StringUtils.join(moderatorsName, ","));
			}
		}
		return m;
	}

	/**
	 *
	 * @Title: postBoards
	 * @Description: 获取当前用户可以发帖的版块信息
	 * @return
	 * @return: List
	 *
	 * @date 2017年11月22日 上午11:50:39
	 *
	 */
	public List postBoards1(String token, String userId, String corpId, String userName,String roles) {
		List<Map> r = new ArrayList<Map>();
		// 检索出所有的版块信息
		List<Map> boards = findAllBoardsOnType(corpId);
		List<String> userInfo = new ArrayList<>();
		if (SecurityUtils.isSuperAdmin(userName)||roles.contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())) {
			for (Map b : boards) {
				r.add(generateChoiceBoardMap(b));
			}
		} else {
			if (!StringUtils.equals(userId, "1")) {
				Map<String, String> textParams = new HashMap<String, String>();
				textParams.put("corpId", corpId);
				textParams.put("id", userId);
				userInfo = orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
				if (CollectionUtils.isEmpty(userInfo)) {
					userInfo = new ArrayList<>();
				}
				userInfo.add(userId);
			}
			// 查询每个版块的 发帖人设置
			StringBuffer sql = new StringBuffer();
			sql.append(
					" select s.scopeType, s.type, s.scopeValue, b.id as boardId from oa_forum_board b, oa_forum_board_user_scope s ");
			sql.append(" where b.id = s.fieldDataValue and s.fieldDataTable = 'oa_forum_board' and b.status = 1 ");
			List<Map> r2 = super.findByListNativeQuery(sql.toString(), null, new HashMap<String, Object>());
			List<String> l1 = new ArrayList<String>(); // 用来存放设置了“发帖人”的版块
			List<String> l2 = new ArrayList<String>(); // 用来存放设置了“发帖人”,切当前用户与权限发帖的版块
			for (Map m : r2) {
				String id1 = m.get("boardId") == null ? "" : m.get("boardId").toString();
				l1.add(id1);
				String t = m.get("scopeType") == null ? "" : m.get("scopeType").toString();
				if (StringUtils.equals(t, "user")) {
					if (StringUtils.equals(m.get("scopeValue").toString(), userId)) {
						l2.add(id1);
					}
					if (userInfo.indexOf(m.get("scopeValue").toString()) >= 0) {
						l2.add(id1);
					}
				} else if (StringUtils.equals(t, "unit") || StringUtils.equals(t, "org")) {
					if (userInfo.indexOf(m.get("scopeValue").toString()) >= 0) {
						l2.add(id1);
					}
				}
			}
			// 对结果进行组装
			// 设置版主不在可发帖人列表中，始终有可发帖权限
			List<String> bs = getUserBoards();
			for (Map b : boards) {
				if (l1.indexOf(b.get("id")) < 0 || l2.indexOf(b.get("id")) >= 0 || bs.indexOf(b.get("id")) >= 0) {
					r.add(generateChoiceBoardMap(b));
				}
			}
		}
		return r;
	}
	
	//获取全文检索的所有可适用范围id
	public List<Map> getSearchPostId(String userId){
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT p.id pid,b.id bid,p.board_id boardId,b.aplication_scope aplication_scope from oa_forum_post p ");
		sql.append(" LEFT JOIN oa_forum_board b on p.board_id = b.id ");
		sql.append(" LEFT JOIN oa_forum_type t ON b.forum_type = t.id ");
		sql.append(" WHERE p.type = '1' AND p.is_delete = '0' ");
		sql.append(" AND b.status = '1' AND b.is_delete = '0' AND t.status = '1' AND t.is_delete = '0' AND (p.check_status = 2 or p.check_status = 4) ");
		Map values = new HashMap<String, Object>();
		String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",values);
		sql.append(" AND " + scopeSql);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, values);
		return list;
	}
	
	public List<Map> postBoardWithDingding(String userId){
		StringBuffer sql = new StringBuffer();
		List<Map> list1 = this.getSearchPostId(userId);
		//查到所有版块
		sql.append(" SELECT b.is_anonymity AS boardIsAnonymity,b.is_petname AS boardIsPetname,b.name as name,b.aplication_scope aplication_scope ,b.id as id FROM oa_forum_board b LEFT JOIN oa_forum_type t on b.forum_type = t.id ");
		sql.append(" WHERE b.is_delete = '0' AND b.STATUS = '1' AND t.status = '1' ");
		Map values = new HashMap<String, Object>();
		String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",values);
		sql.append(" AND " + scopeSql);
		sql.append(" ORDER BY b.createdDate DESC ");
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, values);
		return list;
	}
	
	public Map postBoards(String boardId,String userId) {
		StringBuffer sql = new StringBuffer();
		//查到所有版块
		sql.append(" SELECT b.is_anonymity AS boardIsAnonymity,b.is_petname AS boardIsPetname,b.name as name,b.aplication_scope aplication_scope ,b.id as id FROM oa_forum_board b LEFT JOIN oa_forum_type t on b.forum_type = t.id ");
		sql.append(" WHERE b.is_delete = '0' AND b.STATUS = '1' AND t.status = '1' ");
		Map values = new HashMap<String, Object>();
		String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",values);
		sql.append(" AND " + scopeSql);
		sql.append(" ORDER BY b.createdDate DESC ");
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, values);
		//判断是否管理员或者版主,可以发公告贴,普通用户只有主题帖权限
    	boolean ifAdminOrModerator = true;
    	//进行黑名单 过滤 不允许发帖
    	//获取当前用户
    	Map<String, Object> data = new HashMap();
        WebUser user = WebUtils.getCurrentUser();
        //获取公司id
        String corpId = user.getCorpId();
        String token = user.getJwtToken();
        if(!user.getRoleCodes().contains("appAdminRole")) {
        	if(StringUtils.isNotEmpty(boardId)) {
        		 //查找当前版主集合
                String moderatorScopeValue = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope","oa_forum_board", "id",StringUtils.null2String(boardId));
                String moderatorScopeMap = userApiService.getScopeName(moderatorScopeValue,corpId,token);
                List<String> moderatorList = Arrays.asList(moderatorScopeMap.split(","));
                //如果当前用户不是版主,需要继续判断
                if(!moderatorList.contains(user.getCnName())) {
                	ifAdminOrModerator = false;
                }
        	}else {
        		ifAdminOrModerator = false;
        	}
        }
		Map map = new HashMap();
		map.put("option",list);
		map.put("ifAdminOrModerator", ifAdminOrModerator);
		return map;
	}
	
	/**
	 * 我的帖子显示的版块 不管类别的禁用状态
	 * @return
	 */
	public List postBoardsIngoreStatus(WebUser user) {
		StringBuffer sql = new StringBuffer();
		//查到所有版块
		sql.append( " SELECT b.is_anonymity AS boardIsAnonymity ,b.name as name ,b.id as id FROM oa_forum_board b LEFT JOIN oa_forum_type t on b.forum_type = t.id ");
		sql.append(" WHERE b.is_delete = '0'  ORDER BY b.createdDate DESC  ");
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, new HashMap<String, Object>());
		return list;
	}
	
	
	//根据id去查询版块
	public Map getForumBoard(String id) {
		Map m=new HashMap();
		ForumBoard  forumBoard=forumBoardDao.getForumBoard(id);
		if(null != forumBoard) {
			m.put("text",forumBoard.getName() );
			m.put("value", forumBoard.getId());
		}
		return m;
	}

	private Map generateChoiceBoardMap(Map b) {
		Map m = new HashMap();
		m.put("id", b.get("id"));
		m.put("name", b.get("name"));
		m.put("boardIsAnonymity", b.get("isAnonymity"));
		return m;
	}

	/**
	 * just get username, haven't another infomation
	 * 
	 * @param ids
	 * @param corpId
	 * @param token
	 * @return
	 */
	public Map<String, String> utilQueryUserName(String ids, String corpId, String token) {
		Map<String, String> result = new HashMap<String, String>();
		if (StringUtils.isNotEmpty(ids)) {
			boolean hasAdmin = false;
			List<String> idsList = new ArrayList<String>();
			String[] idarray = ids.split(",");
			for (String i : idarray) {
				if (!StringUtils.equals(i, "1")) {
					idsList.add(i);
				} else {
					hasAdmin = true;
				}
			}
			List<Map<String, Object>> userMap = userApiService.getUserList(ids, corpId, "", token);
			Iterator it = userMap.iterator();
			while (it.hasNext()) {
				Map<String, Object> m = (Map<String, Object>) it.next();
				if (m != null) {
					result.put(StringUtils.null2String(m.get("id")), StringUtils.null2String(m.get("userName")));
				}
			}
			if (hasAdmin) {
				result.put("1", "系统管理员");
			}
		}
		return result;
	}

	public Map<String, String> utilQueryUserName2(String ids, String corpId, String token) {
		Map<String, String> result = new HashMap<String, String>();
		if (StringUtils.isNotEmpty(ids)) {
			boolean hasAdmin = false;
			List<String> idsList = new ArrayList<String>();
			String[] idarray = ids.split(",");
			for (String i : idarray) {
				if (!StringUtils.equals(i, "1")) {
					idsList.add(i);
				} else {
					hasAdmin = true;
				}
			}
			//可查到被删除用户
			List<Map<String, Object>> userMap = userApiService.getUserListIncludeDel(ids, corpId, "", token);
			Iterator it = userMap.iterator();
			while (it.hasNext()) {
				Map<String, Object> m = (Map<String, Object>) it.next();
				if (m != null) {
					result.put(StringUtils.null2String(m.get("id")), StringUtils.null2String(m.get("userName")));
				}
			}
			if (hasAdmin) {
				result.put("1", "系统管理员");
			}
		}
		return result;
	}
	
	public Map<String,Object> findNavigationInfo(String boardId,String corpId,String token){
		Map<String,Object> map = new HashMap<String,Object>();
		ForumBoard board = this.findOne(boardId);
		if(board != null){
			String forumType = board.getForumType();
			ForumType type = forumTypeService.findOne(forumType);
			if(type != null){
				map.put("typeName", type.getName());
			}
			map.put("boardName", board.getName());
			String description = StringUtils.null2String(board.getDescription());
			map.put("description",description);
			String moderatorStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(boardId));
			String moderator = userApiService.getScopeNameIncludeDel(moderatorStr, corpId, token);
			map.put("moderator",moderator);
			map.put("replyCount", forumPostService.getBoardReplyCount(boardId));
			map.put("mainCount", forumPostService.getBoardMainCount(boardId));
		}
		
		return map;
	}

	public int getPostNum(String id, String type, String corpId) {
		String sql = "";
		if(StringUtils.equals(type, "2")) {
			sql = " select p.id from oa_forum_post p left join oa_forum_post op on op.id = p.post_id where p.board_id = :id and p.is_delete = '0' and p.corp_id = :corpId and p.type=:type and (p.check_status in (:status)) and op.check_status in (:status)";
		}else {
			sql = " select id from oa_forum_post where board_id = :id and is_delete = '0' and corp_id = :corpId and type=:type and (check_status in (:status))";
		}
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", corpId);
		paramMap.put("id", id);
		paramMap.put("type", type);
		List<String> checkStatus =new ArrayList<>();
		checkStatus.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		checkStatus.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		paramMap.put("status", checkStatus);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
		if(list != null && !list.isEmpty()) {
			return list.size();
		}else {
			return 0 ;
		}
		
	}

	public boolean checkRecommendTime(String id) {
		ForumBoard board = forumBoardDao.getForumBoard(id);
		if(board!=null&&board.getIsNavigation()==1) {
			return true;
		}
		return false;
	}

	//查询板块下是否有审核中的帖子和审核通过的帖子
	public Map<String,String> ifDelete(String id){
		Map<String ,String> map = new HashMap();
		StringBuffer sql = new StringBuffer();
		//查询 有无 审核通过或者无需审核的的帖子
		sql.append(" select count(*) from oa_forum_post where board_id = :id  ");
		sql.append(" and is_delete='0' and check_status in(2,4) and type='1' ");
		Query query1 =  this.getEntityManager().createNativeQuery(sql.toString());
		query1.setParameter("id",id);
		int count1 = Integer.parseInt(query1.getSingleResult().toString());
		map.put("SHTOorWXSH",count1+"");
		StringBuffer sql1 = new StringBuffer();
		//查询有无审核中的帖子
		sql1.append(" select count(*) from oa_forum_post where board_id = :id  ");
		sql1.append(" and is_delete='0' and check_status = '1' and type='1' ");
		Query query2 =  this.getEntityManager().createNativeQuery(sql1.toString());
		query2.setParameter("id",id);
		int count2 = Integer.parseInt(query2.getSingleResult().toString());
		map.put("SHZ",count2+"");
		return map;
	}
	
	//移动端获取所有版块并将当前帖子的版块的check值设成true;
	public List<Map> getAllBoard(String boardId){
		List<Map> list = new ArrayList<Map>();
		//获取所有版块
		List<ForumBoard> boardList =  forumBoardDao.getALLBoard();
		for(ForumBoard board : boardList) {
			Map map = new HashMap();
			boolean checked=false;
			if(boardId.equals(board.getId())) {
				checked = true;
			}
			map.put("boardId", board.getId());
			map.put("boardName", board.getName());
			map.put("check", checked);
			list.add(map);
		}
		return list;
	}
	
	//判断当前的版块是否还存在
	public boolean boardIfDelete(String id) {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT  is_delete AS isDelete from oa_forum_board where id = :id ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
		Map r = list.get(0);
		if("1".equals(StringUtils.null2String(r.get("isDelete")))) {
			return false;
		}
		return true;
	}
	
	public boolean checkBoardAuthor(String token, String userId, String corpId, String id) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select a.id as boardId,b.id as typeId from oa_forum_board  a ");
		sql.append(" LEFT JOIN oa_forum_type b on a.forum_type = b.id and a.corp_id = b.corp_id and b.is_delete = 0 ");
		sql.append(" LEFT JOIN oa_forum_moderator_scope c on c.fieldDataValue = a.id ");
		sql.append("  where a.corp_id = :corpId and (a.id = :id or b.id = :id) and a.is_delete = 0 and a.status = 1 and b.status = 1 and c.scopeValue = :userId ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", corpId);
		paramMap.put("id", id);
		paramMap.put("userId", userId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
		if(list != null && !list.isEmpty()) {
			return true;
		}else {
			return false;
		}
	}
	
	//获取版块图标
	public String getBoardImg( Object image, String token) {
		String _image = StringUtils.null2String(image);
		String  att = attachmentUtilsService.getAttachmentInfo(_image, token);
		String url = "";
		if(StringUtils.isNoneEmpty(att)) {
			Map<String, Object> result = JsonUtils.readValue(att);
			 url = "attachment/image?fid="+_image+"&chksum="+result.get("checksum").toString();
		}
		return url;
	}
	
	/**
	 * 所有帖子页面获取可适用版块
	 * @param user
	 * @return
	 */
    public List<Map> getBoardMap(WebUser user,String id,String mdpostType) {
    	StringBuffer sql = new StringBuffer();
    	Map<String, Object> paramMap = new HashMap<String, Object>();
		sql.append(" SELECT b.id ,b.name ,b.createdDate,b.aplication_scope aplicationScope ,t.id typeId,t.name typeName from oa_forum_board b ");
		sql.append(" LEFT JOIN oa_forum_type t ON b.forum_type = t.id WHERE b.status = 1 AND t.status = 1 AND b.is_delete = 0 AND t.is_delete = 0 ");
		if("1".equals(mdpostType)) {
			//适用版主sql匹配
			sql.append(" and (b.id in ( select fieldDataValue from oa_forum_moderator_scope where  fieldData='id' and fieldDataTable='oa_forum_board' and scopeValue in  (:userId)))" );
			paramMap.put("userId", user.getUserId());
		}
		if(StringUtils.isNotBlank(id)) {
			sql.append(" AND t.id = :typeid ");
			paramMap.put("typeid", id);
		}
		sql.append(" order by b.createdDate DESC  ");
		List<Map> list = super.findByListNativeQuery(sql.toString(),null, paramMap);
		List<Map> boardList = new ArrayList();
		if(CollectionUtils.isNotEmpty(list)) {
		    for(Map<String,Object> m : list) {
			    if(StringUtils.isNotBlank(StringUtils.null2String(m.get("aplicationScope")))) {
				    String aplicationStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "aplication_scope", StringUtils.null2String(m.get("aplicationScope")));
					//范围为空 所有人都可以用
					if(StringUtils.isNotEmpty(aplicationStr)) {
					    //用户的userId和orgId都不在scope里面的话就说明不在适用范围里面
						if(aplicationStr.indexOf(user.getUserId()) != -1 || aplicationStr.indexOf(user.getOrgId()) != -1) {
							boardList.add(m);
						}
					}else {
						boardList.add(m);
					}
				}else {
					boardList.add(m);
			    }
		    }
		}
		return boardList;
    }

}
